import { reqlogin } from "../../request/api"

const initState={
    user:{
        phone:"",
        password:""
    },
    info:sessionStorage.getItem("info")?JSON.parse(sessionStorage.getItem("info")):{}
}
const types={
    CHANGE_USER:'LOGIN_CHANGEUSER',
    CHANGE_INFO:'LOGIN_CHANGEINFO'
}

const reducer =(state=initState,action)=>{
        switch(action.type){
            case types.CHANGE_USER:
                return {
                    ...state,
                    user:{
                        ...state.user,
                        [action.key]:action.value
                    }
                }
            case types.CHANGE_INFO:
                return {
                    ...state,
                    info:action.info
                }
            default:
                return state
        }
}   

export const actions={
    changeuser:(key,value)=>({type:types.CHANGE_USER,key,value}),

    changeinfo:info=>{
        if(info){
            sessionStorage.setItem('info',JSON.stringify(info))
        }else{
            sessionStorage.removeItem('info')
        }
        return {type:types.CHANGE_INFO,info}
    },

    reqlogin:(history)=>(dispatch,getState)=>{
       
        console.log(getState());
        let {user}=getState().login
        reqlogin(user).then(res=>{
          if(res.data.code===200){

            dispatch(actions.changeinfo(res.data.list))

            history.push('/index/home')
          }
        })
    }
}

//导出数据
export const getuser=(state)=>state.login.user
export const getinfo =state=>state.login.info
export default reducer